<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="行程标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入行程标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:travelItinerary:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:travelItinerary:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:travelItinerary:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:travelItinerary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="travelItineraryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="行程标题" align="center" prop="title" />
      <el-table-column label="行程开始日期" align="center" prop="startDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="行程结束日期" align="center" prop="endDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人数" align="center" prop="personNum" />
      <el-table-column label="联系人" align="center" prop="contactPerson" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="客户单位" align="center" prop="cust" />
      <el-table-column label="行程描述" align="center" prop="description" width="220" />
      <!-- <el-table-column label="类型" align="center" prop="travelType" />
      <el-table-column label="状态" align="center" prop="status" /> -->
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:travelItinerary:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:travelItinerary:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改行程管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="travelItineraryRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="行程标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入行程标题" />
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="2">
            <el-form-item label="人数" prop="personNum">
              <el-input v-model="form.personNum" placeholder="请输入人数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="2">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker clearable
                v-model="form.startDate"
                type="date"
                value-format="YYYY-MM-DD 00:00:00"
                :disabled-date="disabledDate"
                placeholder="请选择行程开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker clearable
                v-model="form.endDate"
                type="date"
                value-format="YYYY-MM-DD 23:59:59"
                :disabled-date="disabledDate"
                placeholder="请选择行程结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="客户单位" prop="cust">
              <el-input v-model="form.cust" placeholder="请输入客户单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="行程描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="center">每日行程信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddDailyItinerary">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteDailyItinerary">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="dailyItineraryList" :row-class-name="rowDailyItineraryIndex" @selection-change="handleDailyItinerarySelectionChange" ref="dailyItinerary" width="800">
          <el-table-column type="selection" width="50" align="center" />
          <!-- <el-table-column label="序号" align="center" prop="index" width="50"/> -->
          <el-table-column label="日期" prop="day" width="180">
            <template #default="scope">
              <el-date-picker
                clearable
                v-model="scope.row.day"
                type="date"
                value-format="YYYY-MM-DD"
                :disabled-date="daliyDisabledDate"
                placeholder="请选择日期"
                style="width: 150px;">
              </el-date-picker>
            </template>
          </el-table-column>

          <el-table-column label="时间段" prop="timeRange" width="280">
            <template #default="scope">
              <div class="demo-time-range">
                  <el-time-select
                    v-model="scope.row.startTime"
                    style="width: 120px"
                    :max-time="scope.row.endTime"
                    class="mr-4"
                    placeholder="开始时间"
                    start="00:00"
                    step="00:10"
                    end="23:50"
                    @change="(time) => handleTimeChange(scope.row)"
                  />
                  <el-time-select
                    v-model="scope.row.endTime"
                    style="width: 120px"
                    :min-time="scope.row.startTime"
                    placeholder="结束时间"
                    start="00:00"
                    step="00:10"
                    end="23:50"
                    @change="(time) => handleTimeChange(scope.row)"
                  />
                </div>
            </template>
          </el-table-column>
          <el-table-column label="类型" prop="travelType" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.travelType" placeholder="请选择类型" @change="handleTypeChange(scope.row);">
                <el-option
                  v-for="dict in travel_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="地点" prop="spotName" width="250">
            <template #default="scope">
              <el-select v-model="scope.row.spotName" placeholder="请选择地点" v-if="scope.row.travelType === '1'" @change="handleSpotChange(scope.row);">
                <el-option
                  v-for="item in spotList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
              <el-input v-model="scope.row.spotName" placeholder="请输入地点" v-else />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TravelItinerary">
import { listTravelItinerary, getTravelItinerary, delTravelItinerary, addTravelItinerary, updateTravelItinerary } from "@/api/manage/travelItinerary";

const { proxy } = getCurrentInstance();

const { travel_type } = proxy.useDict('travel_type');

const travelItineraryList = ref([]);
const dailyItineraryList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedDailyItinerary = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    travelType: null,
    status: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询行程管理列表 */
function getList() {
  loading.value = true;
  listTravelItinerary(queryParams.value).then(response => {
    travelItineraryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    personNum: null,
    contactPerson: null,
    contactPhone: null,
    cust: null,
    description: null,
    travelType: null,
    status: null,
    startDate: null,
    endDate: null,
    createdBy: null,
    updatedBy: null,
    createdAt: null,
    updatedAt: null
  };
  dailyItineraryList.value = [];
  proxy.resetForm("travelItineraryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加行程管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTravelItinerary(_id).then(response => {
    form.value = response.data;
    dailyItineraryList.value = response.data.dailyItineraryList;
    
    // 处理时间范围
    dailyItineraryList.value.forEach(item => {
      item.startTime = item.timeRange.split(' - ')[0];
      item.endTime = item.timeRange.split(' - ')[1];
    })
    open.value = true;
    title.value = "修改行程管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["travelItineraryRef"].validate(valid => {
    if (valid) {
      form.value.dailyItineraryList = dailyItineraryList.value;
      if (form.value.id != null) {
        updateTravelItinerary(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTravelItinerary(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除行程管理编号为"' + _ids + '"的数据项？').then(function() {
    return delTravelItinerary(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 每日行程序号 */
function rowDailyItineraryIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 每日行程添加按钮操作 */
function handleAddDailyItinerary() {
  let obj = {};
  obj.day = "";
  obj.timeRange = "";
  obj.travelType = "";
  obj.spotId = "";
  obj.spotName = "";
  obj.description = "";
  dailyItineraryList.value.push(obj);
}

/** 每日行程删除按钮操作 */
function handleDeleteDailyItinerary() {
  if (checkedDailyItinerary.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的每日行程数据");
  } else {
    const dailyItinerarys = dailyItineraryList.value;
    const checkedDailyItinerarys = checkedDailyItinerary.value;
    dailyItineraryList.value = dailyItinerarys.filter(function(item) {
      return checkedDailyItinerarys.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleDailyItinerarySelectionChange(selection) {
  checkedDailyItinerary.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/travelItinerary/export', {
    ...queryParams.value
  }, `travelItinerary_${new Date().getTime()}.xlsx`)
}

/** 禁用日期 */
const disabledDate = (time) => {
  return time.getTime() < Date.now()
}

const daliyDisabledDate = (time) => {
  const start = form.value.startDate;
  const end = form.value.endDate;

  // 检查开始和结束日期是否为有效日期
  const isValidDate = (date) => date instanceof Date && !isNaN(date);

// 将开始日期设置为该日期的 00:00:00
const startDate = new Date(new Date(start).setHours(0, 0, 0));
// 将结束日期设置为该日期的 00:00:00
const endDate = new Date(new Date(end).setHours(23, 59, 59 ));

  // 确保开始日期和结束日期是有效的日期对象
  if (!isValidDate(startDate) || !isValidDate(endDate)) {
    return false; // 如果日期无效，则不应用禁用规则
  }

  // 判断当前时间是否超出范围
  const state = time.getTime() > endDate.getTime() || time.getTime() < startDate.getTime();
  return state;
}

function handleTimeChange(row) {
  if (row.startTime && row.endTime) {
    row.timeRange = `${row.startTime} - ${row.endTime}`;
  }
}

/** 处理地点选择 */

function handleSpotChange(row) {
  
  const selectedSpot = spotList.value.find(item => item.name === row.spotName);
  if (selectedSpot) {
    row.spotId = selectedSpot.id;
  }
}
function handleTypeChange(row) {
  row.spotId = null;
  row.spotName = null;
  if (row.spotId === null || row.spotId === undefined || row.spotId === '') {
    row.spotId = 0;
  }
}


/** 查询所有景点 */
import {listSpot}  from '@/api/manage/spot'
import {loadAllParams}  from '@/api/page'
import { start } from "nprogress";
import { time } from "echarts";
const spotList = ref([]);
function getSpotList(){
  listSpot(loadAllParams).then(response => {
    spotList.value = response.rows;
  });
}

getSpotList();
getList();
</script>
